<template>
  <div class="container">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="90px" size="mini" class="ruleForm">

      <el-form-item label="市场" prop="market">
        <el-select v-model="ruleForm.market" placeholder="请选择活动区域" @change="changeSelect">
          <el-option v-for="item in optionsData" :key="item.val" :label="''+item.name+''" :value="item.val" />
        </el-select>
      </el-form-item>

      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title"></el-input>
      </el-form-item>
      <el-form-item label="举办单位">
        <el-input v-model="ruleForm.sponsor"></el-input>
      </el-form-item>
      <el-form-item label="承办单位">
        <el-input v-model="ruleForm.organizer"></el-input>
      </el-form-item>
      <el-form-item label="展位数量" prop="boothNum">
        <el-input v-model.number="ruleForm.boothNum"></el-input>
      </el-form-item>
      <el-form-item label="预留展位">
        <el-input v-model="ruleForm.retainBooth"></el-input>
        <span>逗号分开，如连续展位号用-分开，例“1-20,22,33”</span>
      </el-form-item>
      <el-form-item label="举办日期" prop="holdDateType">
        <el-radio-group v-model="ruleForm.holdDateType">
          <el-radio label="1">时间点</el-radio>
          <el-radio label="2">时间段</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="举办时间" required>
        <div v-if="ruleForm.holdDateType == 1">
          <el-row>
            <el-col :span="10">
              <el-form-item>
                <!-- <el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd" @change="holdTime"
                  v-model="ruleForm.holdStartDate" style="width: 100%;"></el-date-picker> -->
                <el-date-picker v-model="holdstartDate" type="date" value-format="yyyy-MM-dd" placeholder="开始日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-time-picker is-range v-model="separatorTime" value-format="hh:mm:ss" range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
              </el-time-picker>
            </el-col>
          </el-row>
        </div>

        <div v-if="ruleForm.holdDateType == 2">
          <el-row>
            <el-col :span="10">
              <el-form-item>
                <el-date-picker v-model="holdstartDateTwo" type="datetimerange" format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期"
                  :default-time="['12:00:00']">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form-item>
      <el-form-item label="举办地址" prop="address" class="address">
        <el-input v-model="ruleForm.address" placeholder="举办地址"></el-input>
        <el-button type="text" @click="dialogMap=true">地图选点</el-button>
      </el-form-item>
      <el-form-item label="乘车路线">
        <el-input v-model="ruleForm.route"></el-input>
      </el-form-item>
      <el-form-item label="联系人">
        <el-input v-model="ruleForm.contact"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="招聘会说明">
        <el-input type="textarea" v-model="ruleForm.remark"></el-input>
      </el-form-item>
      <el-form-item label="预定状态" prop="reserveStatus">
        <el-radio-group v-model="ruleForm.reserveStatus">
          <el-radio label="1">允许预定</el-radio>
          <el-radio label="0">禁止预定</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="isloading" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">返回</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialogMap" width="30%" :show-close='false' class="dialog">
      <span slot='title'>请确认举办地址</span>
      <maps @listenEvent="getLngLat" :address='ruleForm.address' :lat='ruleForm.lat' :lng='ruleForm.lng' ref='HeighMap'
        @handleClose='getDialogMap'>
      </maps>
    </el-dialog>
  </div>
</template>

<script>
import maps from '@/components/common/Map.vue'
import { updateJobFairStatus, getDetails, findMarket } from '../../../api/JobFair';
import { phoneValue } from '@/components/common/validate'
//定义一个全局的变量
var validPhone = (rule, value, callback) => {
  //  else if (!isvalidPhone(value)) {
  //   callback(new Error('请输入正确的11位手机号码'))
  // }
  if (!value) {
    callback(new Error('请输入电话号码'))
  } else if (!phoneValue(value)) {
    callback(new Error('请输入正确的电话号码!'))
  } else {
    callback()
  }
}

export default {
  name: 'editJobFair',
  components: {
    maps
  },
  data () {
    return {
      dialogMap: false,
      // 禁止多次提交
      isloading: false,
      // 市场下拉框
      optionsData: '',
      separatorTime: '',
      holdstartDate: '',
      holdstartDateTwo: '',
      latLng: {},
      ruleForm: {
        address: "",
        boothNum: "",
        contact: "",
        createTime: "",
        deleted: 1,
        time: "",
        holdDateType: '1',
        lat: "",
        lng: "",
        mapZoom: 11,
        market: 1,
        opeId: "1",
        organizer: "",
        phone: "",
        remark: "",
        reserveStatus: '1',
        retainBooth: "",
        route: "",
        sponsor: "",
        title: "",
        topStatus: 1,
        updateTime: "",
        regions: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 150, message: '长度在 2 到 150 个字符', trigger: 'blur' }
        ],
        market: [
          { required: true, message: '请选择市场', trigger: 'change' }
        ],
        // holdTime: [
        //   { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
        // ],
        // holdTime1: [
        //   { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
        // ],
        holdDateType: [
          { required: true, message: '请选举办日期', trigger: 'change' }
        ],
        reserveStatus: [
          { required: true, message: '请选预定状态', trigger: 'change' }
        ],
        boothNum: [
          { required: true, message: '请填写展位数量', trigger: 'blur' },
          { type: 'number', message: '请填写数字', trigger: 'blur' }
          // { min: 1, max: 999, message: '长度在 1 到 999 个数量', trigger: 'blur' },
        ],
        address: [
          { required: true, message: '请填写举办地址', trigger: 'blur' }
        ],
        lat: [
          { required: true, message: '地图未选择', trigger: 'change' }
        ],
        sponsor: [
          { required: true, message: '请填写举办单位', trigger: 'blur' }
        ],
        phone: [
          { required: true, trigger: 'blur', message: '请输入电话', },//这里需要用到全局变量
          { required: true, min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' },
          { validator: validPhone, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    getLngLat (params) {
      console.log(params);
      this.ruleForm.lat = params.lat.toString();
      this.ruleForm.lng = params.lng.toString();
      console.log(this.ruleForm);
    },
    getDialogMap (params) {
      this.dialogMap = params;
    },
    // 时间
    holdTime (data) {
      this.ruleForm.holdTime[0] = data;
    },
    // 验证是否有中文逗号
    contains (str, subStr, isIgnoreCase) {

      if (isIgnoreCase) {
        // 忽略大小写  
        str = str.toLowerCase();
        subStr = subStr.toLowerCase();
      }
      var startChar = subStr.substring(0, 1);
      var strLen = subStr.length;

      for (var j = 0; j < str.length - strLen + 1; j++) {
        if (str.charAt(j) == startChar) {
          /* 如果匹配起始字符,开始查找 */
          if (str.substring(j, j + strLen) == subStr) {
            /*如果从j开始的字符与 str 匹配 */
            return true;
          }
        }
      }
      return false;
    },
    // 提交
    submitForm (formName) {
      let that = this
      that.isloading = true
      const loading = that.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.2)'
      });
      that.$refs[formName].validate((valid) => {
        if (valid) {
          if (that.ruleForm.boothNum > 999) {
            that.$message('展位数量不能超过999个')
            loading.close()
            that.isloading = false
            return false
          }
          if (that.ruleForm.retainBooth) {
            if (that.contains(that.ruleForm.retainBooth, "，", true)) {
              that.$message.error("预留展位,含有中文逗号,请改为英文逗号");
              loading.close();
              that.isloading = false
              return false
            }
            // 针对预留展位去重
            that.ruleForm.retainBooth = Array.from(new Set(that.ruleForm.retainBooth.split(','))).join(',')
          }

          if (!that.ruleForm.lat) {
            that.$message.error('请选择地图位置')
            loading.close()
            that.isloading = false
            return false
          }
          console.log('1', that.holdstartDate, '日期', that.separatorTime, '时间段')
          that.ruleForm.holdDateType = Number(that.ruleForm.holdDateType)
          if (that.ruleForm.holdDateType == 1) {
            if (!that.holdstartDate) {
              that.$message.error('请选择开始日期')
              loading.close()
              that.isloading = false
              return false
            }
            if (!that.separatorTime) {
              that.$message.error('请选择开始时间-结束时间')
              loading.close()
              that.isloading = false
              return false
            }
            that.ruleForm.holdStartDate = that.holdstartDate
            that.ruleForm.holdStartTime = that.separatorTime[0]
            that.ruleForm.holdEndTime = that.separatorTime[1]
            that.ruleForm.holdEndDate = null
          } else {
            if (!that.holdstartDateTwo) {
              loading.close()
              that.isloading = false
              that.$message.error('请选择举办时间')
              return false
            }
            console.log(that.holdstartDate, 'holdstartDate')
            that.ruleForm.holdStartDate = that.holdstartDateTwo[0].split(' ')[0]
            that.ruleForm.holdStartTime = that.holdstartDateTwo[0].split(' ')[1]

            that.ruleForm.holdEndDate = that.holdstartDateTwo[1].split(' ')[0]
            that.ruleForm.holdEndTime = that.holdstartDateTwo[1].split(' ')[1]
          }
          that.updateJobFairStatus(that.ruleForm)
        } else {
          console.log('error submit!!');
          loading.close()
          that.isloading = false
          return false;
        }
      });
    },
    resetForm (formName) {
      this.$refs[formName].resetFields();
      this.$router.go(-1)
    },
    // 获取详情信息 接口
    getDetails () {
      let id = this.$route.query.id
      console.log(id, 'id123')
      if (!id) return false
      getDetails(id).then((data) => {
        if (data.success) {
          let datas = data.data
          if (datas.holdDateType == 1) {
            this.holdstartDate = datas.holdStartDate
            this.separatorTime = [datas.holdStartTime, datas.holdEndTime]
          } else {
            this.holdstartDateTwo = [datas.holdStartDate + ' ' + datas.holdStartTime, datas.holdEndDate + ' ' + datas.holdEndTime]
          }
          // 赋值地区坐标
          datas.holdDateType = String(datas.holdDateType)
          datas.reserveStatus = String(datas.reserveStatus)
          this.latLng = {
            lat: datas.lat,
            lng: datas.lng
          }
          this.ruleForm = datas
          this.findMarket()
          console.log(data, '请求回来的参数')
        }
      })
    },
    // 更新详情信息接口
    updateJobFairStatus (obj) {
      let loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.1)'
      });
      updateJobFairStatus(obj).then((data) => {
        if (data.success) {
          this.isloading = false
          this.$router.push({
            path: '/JobFairList'
          })
          loading.close()
          console.log(data, '请求回来的参数')
        } else {
          loading.close()
          this.isloading = false
          this.$message.error(data.msg)
        }
      }).catch((err) => {
        loading.close()
        this.isloading = false
        this.$message.error(err.msg)
      })
    },
    // 市场下拉框接口
    findMarket () {
      findMarket().then((res) => {
        if (res.success) {
          this.optionsData = res.data
          this.optionsData.map((item) => {
            // 与后端修改的数据 做对应显示出来
            if (item.val == this.ruleForm.market) {
              this.ruleForm.regions = item.val
              this.$forceUpdate() // 更新dom
            }
          })
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 地图坐标赋值
    listenEvent (e) {
      this.ruleForm.lat = e.lat
      this.ruleForm.lng = e.lng
    },
    changeSelect (e) {
      this.ruleForm.regions = e
      this.$forceUpdate() // 更新dom
      console.log(this.ruleForm.regions, 'this.ruleForm.region')
    }
  },
  created () {
    // this.findMarket()
    this.getDetails()
  },
  mounted () {
    // this.getDetails()
  },
  watch: {
    '$route.query.id': function (val, oldVal) {
      console.log(val, 'val')
      this.$nextTick(() => {
        this.getDetails();
      })
    }
  },
}
</script>

<style scoped>
.ruleForm {
    width: 30%;
}
.grid-content-map {
    width: 435px;
    height: 200px;
    background: indianred;
}
.dialog {
    height: 600px;
}
.dialog /deep/ .el-dialog__header {
    font-size: 14px;
    padding: 10px 0 5px 10px;
}
.dialog /deep/ .el-dialog__body {
    width: 100%;
    padding: 0;
    height: 100%;
}
.address {
    margin-bottom: 40px;
}
.address /deep/ .el-button {
    position: absolute;
    top: 40px;
    left: 0;
}
</style>